package com.feihong.yw189.activity.shouye;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SDCardUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.WebInterface.AjaxWebInterface;
import com.feihong.yw189.activity.WebInterface.MoreWebInterface;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.tiaoxingma.IMEITiaoXingMaActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.activity.SearchBlueActivity;
import com.feihong.yw189.bluetooth.bean.Data;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.http.FileUploader;
import com.feihong.yw189.http.FileUploaderCallBack;
import com.feihong.yw189.http.Host;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.Kaika.UpLoadPicModel;
import com.feihong.yw189.paidan.qiangdanservice.LocationCallBack;
import com.feihong.yw189.paidan.qiangdanservice.LocationInfo;
import com.feihong.yw189.paidan.qiangdanservice.LocationToolsOnces;
import com.feihong.yw189.utils.CustomServiceUtil;
import com.feihong.yw189.utils.PhotoUtils;
import com.feihong.yw189.utils.UserLoginInfo;
import com.feihong.yw189.view.WebView4Scroll;
import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.meiqia.meiqiasdk.imageloader.MQImage;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import txgw.feihong.com.txgwlibrary.mqglide_loader.MQGlideImageLoader4;

import static com.feihong.yw189.activity.tiaoxingma.TiaoXingMaActivity.INTENT_ICCID;

/**
 * @author wangziheng
 * @Description
 * @Data 2018/10/19
 */
@RuntimePermissions
public class MoreActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_goback)
    RelativeLayout rlGoback;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.iv_confirm)
    TextView tvFanli;
    @BindView(R.id.webviewframe)
    RelativeLayout webviewFrame;
    @BindView(R.id.swiperefreshlayout)
    SwipeRefreshLayout mswiperefreshlayout;


    private Unbinder unbinder;
    private Intent mInetent;
    //拍照
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private int photoType = 0;
    //0拍照 1相册
    private static final int ZCODE_SCAN_INTENT_CODE = 10;
    private File fileUri = null;
    private File file_wenjian = null;
    BaseBottomDialog dialog = null;
    MyUsualyDialog mYdialog;
    private String type_img;
    private String mcallBack;

    private static final int CODE_READ_IDNUMBER = 1550;
    CustomServiceUtil customServiceUtil;
    Intent customeServiceIntent;
    private String imgurl;

    /**
     * 定位是否成功
     */
    private boolean isLocationSuccess = false;
    /**
     * 当前界面是否需要定位功能
     */
    private boolean isNeedLocatoinCurrentPage = false;
    /**
     * 经纬度
     */
    private String mLat, mLon;
    /**
     * 获取经纬度的方法
     */
    private LocationToolsOnces mLocationToolsOnces;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_webview);
        unbinder = ButterKnife.bind(this);
        customServiceUtil = new CustomServiceUtil();
        initView();
        bindData();
    }

    @Override
    public void setTheme() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    public void initView() {
        //setBackButtonFinish();
        ivLin.setVisibility(View.GONE);
        tvFanli.setVisibility(View.GONE);
        mInetent = new Intent();
        mYdialog = new MyUsualyDialog(this, R.layout.wait_item);

        // AgentWeb 保持了 WebView 的使用 ，
        //设置刷新时动画的颜色，可以设置4个
        mswiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mswiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);

        mswiperefreshlayout.setEnabled(false);
    }

    private void bindData() {
        if (mAgentWeb == null) {
            WebView4Scroll webView4Scroll = new WebView4Scroll(getActivity(), mswiperefreshlayout);
            webView4Scroll.setVerticalScrollBarEnabled(false);
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(webviewFrame, new LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .setWebViewClient(mWebViewClient)
                    .setWebChromeClient(webChromeClient)
                    .setMainFrameErrorView(R.layout.agentweb_errorlayout, R.id.agentweb_re_query_data_layout)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .createAgentWeb()
                    .ready()
                    .go(HttpTools.SHOUYE_MORE + "?token=" + UserLoginInfo.getUserLoginInfoInstance().getUserToken() + "&version=" + "and." + AppUtils.getAppVersionName());

            mAgentWeb.getAgentWebSettings().getWebSettings().setGeolocationEnabled(false);

            jsCallJava();

        } else {
            mAgentWeb.getWebCreator().getWebView().setVisibility(View.VISIBLE);
            mAgentWeb.getUrlLoader().reload();
        }
    }

    WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title)) {
                setPageTitle(title);
            } else {
                setPageTitle("更多");
            }
        }
    };

    private void jsCallJava() {

        //添加Ajax数据请求的接口
        mAgentWeb.getJsInterfaceHolder().addJavaObject(AjaxWebInterface.AJAX_KEY, new AjaxWebInterface(this, mAgentWeb.getJsAccessEntrace()));

        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new MoreWebInterface(mAgentWeb, this, new ActionCallBack() {

            @Override
            public void go_back() {
                Log.i(TAG, "go_back: 返回 ");
                runOnUiThread(() -> {
                    if(!mAgentWeb.back()){
                        finish();
                    }
                });

            }

            @Override
            public void getZCode(String info) {
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    // 获取要扫描的类型  barcode 条形码     qrcode 二维码
                    jsonObject.optString("type");
                    methodName = null;
                    methodName = jsonObject.optString("success");
                    if (TextUtils.isEmpty(methodName)) {
                        methodName = "success";
                    }
                    Intent intent = new Intent(MoreActivity.this, IMEITiaoXingMaActivity.class);
                    startActivityForResult(intent, ZCODE_SCAN_INTENT_CODE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void refresh_gps() {
                isNeedLocatoinCurrentPage = true;
                MoreActivityPermissionsDispatcher.requestLocaitonPerWithCheck(MoreActivity.this);
            }

            // 刷身份证
            @Override
            public String get_card(String info) {
                try {
                    Log.i(TAG, "get_card: " + info);
                    JSONObject jsonObject = new JSONObject(info);
                    mcallBack = jsonObject.optString("callback");
                    mInetent.setClass(getActivity(), SearchBlueActivity.class);
                    mInetent.putExtra("isTest", "0");
                    startActivityForResult(mInetent, CODE_READ_IDNUMBER);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return "";
            }

            // 相机
            @Override
            public Boolean get_images(String info) {
                fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/takepic.jpg");
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    type_img = jsonObject.optString("type");
                    mcallBack = jsonObject.optString("callback");

                } catch (Exception e) {
                }
                if (type_img.equals("1")) {
                    takePhoto(0);
                } else if (type_img.equals("2")) {
                    takePhoto(1);

                } else if (type_img.equals("3")) {
                    dialogChoose();
                }
                return false;
            }

            // 联系客服
            @Override
            public String get_service(String info) {

                MQImage.setImageLoader(new MQGlideImageLoader4());
                customeServiceIntent = new MQIntentBuilder(getApplication())
                        .setClientInfo(customServiceUtil.queryConfig())
                        .build();
                startActivity(customeServiceIntent);

                return "";
            }

            @Override
            public String lt_qdpd() {
                /*Intent mIntent = new Intent(MoreActivity.this, DispatchActivity.class);
                startActivity(mIntent);*/
                return "";
            }

            /**复制粘贴到剪切板
             * */
            @Override
            public String copy_text(String info) {
                // showInfoToast(funcName);
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(info);
                return "";
            }

            /**保存本地交互
             * */
            @Override
            public String dow_images(String info) {
                // showInfoToast(funcName);
                try {
                    JSONObject jsonObject = new JSONObject(info);
                    imgurl = jsonObject.optString("url");
                    if (!TextUtils.isEmpty(imgurl)) {
                        imgurl = Host.HTTP_HOME + imgurl + "&token=" + UserLoginInfo.getUserLoginInfoInstance().getUserToken();
                        new SaveImage().execute(); // Android 4.0以后要使用线程来访问网络
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return "";
            }

            @Override
            public void netWork(String info) {
                HashMap<String, String> mParams = new HashMap<>();
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(info);
                String url = jsonObject.getString("url");
                if (TextUtils.isEmpty(url)) {
                    return;
                }
                mParams.put("url", url);
                com.alibaba.fastjson.JSONObject params = jsonObject.getJSONObject("data");
                if (params != null) {
                    Set<Map.Entry<String, Object>> paramsSet = params.entrySet();
                    if (paramsSet.size() > 0) {
                        Iterator<Map.Entry<String, Object>> iterator = paramsSet.iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, Object> entry = iterator.next();
                            mParams.put(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString());
                        }
                    }

                }
                url = jsonObject.getString("url");
                errorMethodName = jsonObject.getString("error");
                int timeOut = Integer.valueOf(jsonObject.getString("timeout"));
                methodName = null;
                methodName = jsonObject.getString("success");
                App.getApp().getHttpTools().ajaxPost(url, mParams, timeOut, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if (TextUtils.isEmpty(methodName)) {
                            methodName = "success";
                        }
                        if (mAgentWeb != null) {
                            mAgentWeb.getJsAccessEntrace().quickCallJs(methodName + "(" + result + ")");
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        if (TextUtils.isEmpty(errorMethodName)) {
                            errorMethodName = "error";
                        }
                        if (mAgentWeb != null) {
                            mAgentWeb.getJsAccessEntrace().quickCallJs(errorMethodName + "()");
                        }
                        showToast(getResources().getString(R.string.connect_sever_error_toast));
                    }

                    @Override
                    public void onCancelled(Callback.CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        }));
    }

    @Override
    protected void onResume() {
        super.onResume();
        //  主要用于检测定位开卡是否开启
        if (isNeedLocatoinCurrentPage) {
            MoreActivityPermissionsDispatcher.requestLocaitonPerWithCheck(this);
        }
    }

    /**
     * 请求成功 要调用的方法名
     */
    String methodName;
    /**
     * 请求失败要调用的方法名
     */
    String errorMethodName;
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @SuppressLint("NewApi")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (url.contains("DxApp/ShopInfo/index.html")) {
                isNeedLocatoinCurrentPage = true;
            } else {
                isNeedLocatoinCurrentPage = false;
            }
            super.onPageFinished(view, url);

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };

    @Override
    @OnClick({R.id.rl_goback})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_goback:
                if (!mAgentWeb.back()) {
                    finish();
                }
                break;
            case R.id.user_take_photo:
                //拍照
                takePhoto(0);
                dialog.dismiss();
                break;
            case R.id.user_select_from_lib:
                //相册
                takePhoto(1);
                dialog.dismiss();
                break;
            case R.id.user_photo_cancel:
                //取消
                dialog.dismiss();
                break;
            default:
                break;
        }
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Needs() {
        switch (photoType) {
            case 0:
                // takePhoto();
                openCamera();
                break;
            case 1:
                PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                break;
            default:
                break;
        }
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MoreActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Rationale(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onPermissionDenied() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void AskAgain() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }


    public interface ActionCallBack {

        String get_card(String info);

        Boolean get_images(String info);

        String get_service(String info);

        String lt_qdpd();

        String copy_text(String info);

        String dow_images(String info);

        void netWork(String info);

        void getZCode(String info);

        /**
         * 刷新经纬度
         */
        void refresh_gps();

        /**
         * 界面返回
         */
        void go_back();
    }

    @Override
    protected void onDestroy() {
        if (mLocationToolsOnces != null) {
            mLocationToolsOnces.stopLocation();
        }
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (mAgentWeb != null) {
            mAgentWeb.destroy();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST:
                    //拍照完成回调
                    if (fileUri != null) {
                        file_wenjian = new File(fileUri.getAbsolutePath());
                        if (file_wenjian != null || file_wenjian.exists()) {
                            submitPic();
                        } else {
                            showErrorToast("请拍照上传身份证");
                            return;
                        }
                    }
                    break;
                case CODE_READ_IDNUMBER:
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        if (!TextUtils.isEmpty(mcallBack)) {

                            byte[] photo = bundle.getByteArray("photo");
                            Bitmap bitmap = BitmapFactory.decodeByteArray(photo, 0, photo.length);

                            // 将参数封装进Data对象，然后转成json
                            Data dataInfo = new Data();
                            dataInfo.setAddress(bundle.getString("address"));
                            // 图片
                            dataInfo.setPhoto(bundle.getString("photoHeard"));
                            dataInfo.setSex(bundle.getString("sex"));
                            dataInfo.setIdcardno(bundle.getString("id_num"));
                            // 民族
                            dataInfo.setNation(bundle.getString("nation"));
                            // 签发机关
                            dataInfo.setGrantdept(bundle.getString("sign_office"));
                            // 有效期的开始时间
                            dataInfo.setTo(bundle.getString("to"));
                            dataInfo.setuSAMID("00000");
                            // 名字
                            dataInfo.setName(bundle.getString("name"));
                            // 有效期的截止日期
                            dataInfo.setForm(bundle.getString("from"));
                            // 生日
                            dataInfo.setBorn(bundle.getString("born"));

                            Gson gson = new Gson();
                            String dddata = gson.toJson(dataInfo);
                            mAgentWeb.getJsAccessEntrace().quickCallJs(mcallBack, dddata);

                            //showToast(mcallBack+"");
                        }
                    } else {
                        showErrorToast("读取失败,请重试!");
                    }
                    break;
                case ZCODE_SCAN_INTENT_CODE:
                    String resultNum = data.getStringExtra(INTENT_ICCID);
                    String jsonStr = JSON.toJSONString(resultNum);
                    Log.i(TAG, "onActivityResult: " + jsonStr);
                    mAgentWeb.getJsAccessEntrace().quickCallJs(methodName + "(" + jsonStr + ")");

                    break;
                default:
                    break;
            }
        }
    }

    /*------------------拍照------------*/
    private void takePhoto(int Type) {
        try {
            String sdCardPath = SDCardUtils.getSDCardPathByEnvironment();
            if (TextUtils.isEmpty(sdCardPath)) {
                showErrorToast("SD卡不可用，请检查权限是否给全！");
                return;
            }
            File dirPath = new File(sdCardPath + "/YW189/");
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File filePath = new File(dirPath.getAbsolutePath() + "/zhaopian.jpg");
            if (filePath == null) {
                return;
            }
            fileUri = filePath;
            photoType = Type;
            MoreActivityPermissionsDispatcher.NeedsWithCheck((MoreActivity) getActivity());
        } catch (Exception ex) {
            ex.printStackTrace();
            showErrorToast("出错：无法创建制定的文件夹，请重试！");
        }
    }

    /***
     * 开始打开照相机
     */
    private void openCamera() {
        PhotoUtils.takePicture(this, fileUri, CODE_CAMERA_REQUEST);
    }


    /**
     * 拍照相册选择dialog
     */
    private void dialogChoose() {
        dialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.activity_my_photo_edit)
                .setDimAmount(0.5f)
                // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                .setCancelOutside(false)
                // 点击外部区域是否关闭，默认true
                .setTag("BottomDialog")
                // 设置DialogFragment的tag
                // 可以进行一些必要对View的操作
                .setViewListener(v -> dialogClick(v))
                .show();
    }

    private void dialogClick(View v) {
        v.findViewById(R.id.user_take_photo).setOnClickListener(this);
        v.findViewById(R.id.user_select_from_lib).setOnClickListener(this);
        v.findViewById(R.id.user_photo_cancel).setOnClickListener(this);
    }


    /***
     * 上传图片 第一步  上传正面图片
     */
    private void submitPic() {

        mYdialog.show();
        FileUploader fileUploader = new FileUploader(this);
        try {
            fileUploader.uploadFile(1001, file_wenjian.getAbsolutePath(), new FileUploaderCallBack() {
                @Override
                public void success(int req, String path, UpLoadPicModel model, String result) {

                    mYdialog.dismiss();
                    showToast("上传成功");
                    mAgentWeb.getJsAccessEntrace().quickCallJs(mcallBack, result);
                }

                @Override
                public void error(int req, String path, String error) {
                    mYdialog.dismiss();
                    showErrorToast(error);
                }
            });
        } catch (Exception ex) {
            mYdialog.dismiss();
            showErrorToast("处理失败，请重试!错误代码:1001");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!mAgentWeb.back()) {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /***
     * 功能：用线程保存图片
     * @author wangyp
     */
    public class SaveImage extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = "";
            try {
                String sdcard = Environment.getExternalStorageDirectory().toString();
                File file = new File(sdcard + "/Download");
                if (!file.exists()) {
                    file.mkdirs();
                }
                int idx = imgurl.lastIndexOf(".");
                String ext = imgurl.substring(idx);
                file = new File(sdcard + "/Download/zcod.jpg");
                InputStream inputStream = null;
                URL url = new URL(imgurl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20000);
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                }
                byte[] buffer = new byte[4096];
                int len = 0;
                FileOutputStream outStream = new FileOutputStream(file);

                while ((len = inputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                //保存图片后发送广播通知更新数据库
                Uri uri = Uri.fromFile(file);
                MoreActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                outStream.close();
                result = "图片已保存至：" + file.getAbsolutePath();
            } catch (Exception e) {
                result = "保存失败！" + e.getLocalizedMessage();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            showToast(result);
        }
    }


    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void requestLocaitonPer() {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!ok) {
            new AlertDialog.Builder(this)
                    .setPositiveButton("去打开", (dialog1, which) -> {
                                Intent intenta = new Intent();
                                intenta.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivityForResult(intenta, 1315);
                            }
                    )
                    .setNegativeButton("退出", (dialog1, which) -> mAgentWeb.back())
                    .setCancelable(false)
                    .setMessage("位置服务开关未打开")
                    .show();
        } else {
            mLocationToolsOnces = new LocationToolsOnces(this, mLocationCallBack);
            mLocationToolsOnces.startLocation(0);
        }
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showRational(final PermissionRequest request) {
        request.proceed();
    }

    /**
     * 定位监听
     */
    LocationCallBack mLocationCallBack = new LocationCallBack() {
        @Override
        public void successGetLocation(LocationInfo info) {
            if (activityIsDestory()) {
                return;
            }
            isLocationSuccess = true;
            mLat = String.valueOf(info.getLatitude());
            mLon = String.valueOf(info.getLongitude());
            UserLoginInfo.getUserLoginInfoInstance().setLocationLat(mLat);
            UserLoginInfo.getUserLoginInfoInstance().setLocationLon(mLon);
            mAgentWeb.getJsAccessEntrace().quickCallJs("get_gps", mLon, mLat);
        }

        @Override
        public void error(String error) {
            if (activityIsDestory()) {
                return;
            }
            mLat = null;
            mLon = null;
            isLocationSuccess = false;
            mAgentWeb.getJsAccessEntrace().quickCallJs("get_gps");
            switch (error) {
                case "4":
                case "5":
                    showSystemToast("定位失败,请检查网络");
                    break;
                case "12":
                    showSystemToast("请开启app的定位权限");
                    break;
                case "13":
                    showSystemToast("定位失败,请检查网络以及定位权限是否授予");
                    break;
                case "14":
                    showSystemToast("定位失败,请到相对开阔的露天场所再次尝试");
                    break;
                case "18":
                    showSystemToast("定位失败,建议手机关闭飞行模式，并打开WIFI开关");
                    break;
                case "19":
                    showSystemToast("定位失败,建议手机插上sim卡，并打开WIFI开关");
                    break;
                default:
                    showSystemToast("定位失败,请退出当前界面重试");
                    break;
            }
        }
    };

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void Denied() {
        ToastUtils.showShortToast(MoreActivity.this, "权限不足,您没有开启此应用的定位权限。请到系统设置-->权限管理 开启定位权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下定位权限！");
        if (mAgentWeb != null) {
            mAgentWeb.back();
        }
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void AskAgin() {
        ToastUtils.showShortToast(MoreActivity.this, "权限不足,您没有开启此应用的定位权限。请到系统设置-->权限管理 开启定位权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下定位权限！");
        if (mAgentWeb != null) {
            mAgentWeb.back();
        }
    }

}